package com.lx.tomcat.contained;

import com.lx.tomcat.lifecycle.LifecycleBase;
import com.lx.tomcat.lifecycle.LifecycleState;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

public abstract class ContainerBase extends LifecycleBase implements Container{

    protected String name;
    protected Container container;
    protected final ConcurrentHashMap<String,Container> children = new ConcurrentHashMap<>();

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Container getParent() {
        return container;
    }

    @Override
    public void setParent(Container container) {
        this.container = container;
    }

    @Override
    public void addChild(Container child) {
        children.put(child.getName(),child);
    }

    @Override
    public Collection<Container> findChildren() {
        return children.values();
    }
    @Override
    public void init() throws Exception {
        if (!getState().equals(LifecycleState.NEW)) {
            throw new RuntimeException("请先进行初始化操作");
        }
        setLifecycleState(LifecycleState.INIT);
        initInternal();
        setLifecycleState(LifecycleState.INITED);
    }

    @Override
    public void start() throws Exception {
        setLifecycleState(LifecycleState.START);
        startInternal();
        setLifecycleState(LifecycleState.STARTED);
    }

    @Override
    public void stop() throws Exception {
        setLifecycleState(LifecycleState.STOP);
        stopInternal();
        setLifecycleState(LifecycleState.STOPED);
    }

    @Override
    public void destroy() throws Exception {
        setLifecycleState(LifecycleState.DESTORY);
        destroyInternal();
        setLifecycleState(LifecycleState.DESTORYED);
    }

    @Override
    protected void initInternal() throws Exception {
        for (Container child : findChildren()) {
            child.init();
        }
    }

    @Override
    protected void startInternal() throws Exception {
        for (Container child : findChildren()) {
            child.start();
        }
    }

    @Override
    protected void stopInternal() throws Exception {
        for (Container child : findChildren()) {
            child.stop();
        }
    }

    @Override
    protected void destroyInternal() throws Exception {
        for (Container child : findChildren()) {
            child.destroy();
        }
    }

    @Override
    public void setLifecycleState(LifecycleState lifecycleState) {
        System.out.println(getName()+" "+lifecycleState);
        super.setLifecycleState(lifecycleState);
    }

}
